#include "mqttclient.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDateTime>
#include <QTimer>

// 示例
// MqttClient *mqtt = new MqttClient("120.26.201.192", 1883, "root");
MqttClient::MqttClient(QString ip, quint16 port, QString user_name, QObject *parent) : QObject(parent)
{
    this->clientId = user_name;
    m_client = new QMqttClient(this);

    // 设置遗嘱消息
    QJsonObject willJson;
    willJson["farm_id"] = clientId;
    willJson["status"] = "off";
    willJson["time_stamp"] = QDateTime::currentDateTime().toString("yy-MM-dd hh-mm-ss");

    m_client->setWillMessage(QJsonDocument(willJson).toJson(QJsonDocument::Compact));
    m_client->setWillTopic("smartfarm/" + clientId + "/user/status");
    m_client->setWillQoS(0);
    m_client->setWillRetain(true);

    m_client->setHostname(ip);
    m_client->setPort(port);

   connect(m_client, &QMqttClient::connected, this, &MqttClient::on_connected);



   connect(m_client, &QMqttClient::disconnected, [this](){
       qDebug() << "mqtt重连失败，等待重连";
       QTimer::singleShot(1000, this, [this]() {
           if (this->m_client->state() == QMqttClient::Disconnected) {
               this->m_client->connectToHost();
           }
       });
   });

   connect(m_client, &QMqttClient::messageReceived, this, &MqttClient::new_message);
//   firstConnect = false;
//   connect(m_client, &QMqttClient::errorChanged,[this](QMqttClient::ClientError error){
//       if (error == QMqttClient::TransportInvalid && !firstConnect) {
//               qDebug() << "MQTT 首次连接失败，重连中";
//               firstConnect = true;
//               emit this->m_client->disconnected();
//           }
//   });
   connect(m_client, &QMqttClient::errorChanged, this, [this]() {
       qDebug() << "MQTT error:" << m_client->error();
   });

m_client->connectToHost();

}


void MqttClient::new_message(const QByteArray &message, const QMqttTopicName &topic){
    QString topicStr = topic.name();
    QStringList parts = topicStr.split('/');
    QString wildcardMatch = parts[1];  // 获取+通配符匹配的部分
    qDebug() << topic.name() << "==>";
    if(topicStr.endsWith("/sensor/data")) {
        qDebug() << "农场ID:" << wildcardMatch << "数据:" << message;
    }
    else if(topicStr.endsWith("/constantValue/data")) {
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(message, &parseError);
        emit achievedConstantValue(doc["farm_id"].toInt(), doc["co2"].toDouble(),
                doc["temperature"].toDouble(), doc["humidity"].toDouble(), doc["light_intensity"].toDouble());
    }
    else if(topicStr.endsWith("/controller/status")) {
        qDebug() << "农场ID:" << wildcardMatch << "数据:" << message;
    }
    else {
        qDebug() << "格式错误:" << topicStr << "Message:" << message;
    }
}

void MqttClient::getConstantValue(int farm_id){
    QJsonObject setValue;
    setValue["farm_id"] = farm_id;
    setValue["time_stamp"] = getTimeStemp();

    m_client->publish("smartfarm/"+ QString::number(farm_id) +"/getConstantValue/cmd", QJsonDocument(setValue).toJson(QJsonDocument::Compact));
}

void MqttClient::setConstantValue(int farm_id, float co2, float temperature, float humidity, float light_intensity){
    QJsonObject setValue;
    setValue["farm_id"] = farm_id;
    setValue["co2"] = co2;
    setValue["temperature"] = temperature;
    setValue["humidity"] = humidity;
    setValue["light_intensity"] = light_intensity;
    setValue["time_stamp"] = getTimeStemp();

    m_client->publish("smartfarm/"+ QString::number(farm_id) +"/setConstantValue/cmd", QJsonDocument(setValue).toJson(QJsonDocument::Compact));
    return;
}

void MqttClient::setConstantValueco2(int farm_id, float co2)
{
    QJsonObject setValue;
    setValue["farm_id"] = farm_id;
    setValue["co2"] = co2;
    setValue["time_stamp"] = getTimeStemp();
    m_client->publish("smartfarm/"+ QString::number(farm_id) +"/setConstantValue/cmd", QJsonDocument(setValue).toJson(QJsonDocument::Compact));
    return;
}



void MqttClient::send_message(const QMqttTopicName &topic, const QJsonObject &jsonPlayd){

    // 重新序列化
    QJsonDocument newDoc(jsonPlayd);
    QByteArray newPayload = newDoc.toJson(QJsonDocument::Compact);
    // 发布消息
    auto result = m_client->publish(topic, newPayload, 0, false);
    if (result == -1) {
        qWarning("Mqtt 发送失败");
    }
}

QString MqttClient::getTimeStemp(){
    return QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss");
}

void MqttClient::send_message(const QMqttTopicName &topic, const QString &playd){
    // 解析原始 JSON
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(playd.toUtf8(), &err);
    if (err.error != QJsonParseError::NoError || !doc.isObject()) {
        qWarning("Invalid JSON payload: %s", qPrintable(playd));
        return;
    }

    QJsonObject obj = doc.object();

    // 添加时间戳
    obj["time_stemp"] = getTimeStemp();

    send_message(topic, obj);
}

// 连接成功即调用
void MqttClient::on_connected(){
    qDebug() << "mqtt 连接成功";

    // 上线消息
    QJsonObject onlineJson;
    onlineJson["farm_id"] = clientId;
    onlineJson["status"] = "on";
    onlineJson["time_stamp"] = getTimeStemp();
    m_client->publish("smartfarm/" + clientId + "/user/status", QJsonDocument(onlineJson).toJson(QJsonDocument::Compact),1,true);

    m_client->subscribe(QString("smartfarm/+/sensor/data"), 0);
    m_client->subscribe(QString("smartfarm/+/constantValue/data"), 0);
    m_client->subscribe(QString("smartfarm/+/controller/status"), 0);
    qDebug()<<"connect successful";

}
